<template>
  <table-index :table="table" :rowKey="`id`" @loadData="loadData">
    <template #table-summary>
      <a-alert style="margin-right: 20px"> 车型价格设置规范及反写操作较为重要且容易出错，仅支持电脑端操作，可在APP端查看反写结果 </a-alert>
    </template>
    <template #table-header-after>
      <!-- 操作引导 -->
      <guide v-if="userStore.epChannelPriceSync" />
    </template>
    <!-- 模板名称 -->
    <template #templateName="{ record }">
      <templateName :record="record" :queryParam="queryParam" />
    </template>
    <!-- 门店数量 -->
    <template #siteNum="{ record }">
      <div class="site-num-wrapper">
        <span class="site-num-val">{{ record.templateType == 1 ? '全部' : record.siteNum }}</span>
        <a-button type="outline" size="mini" class="view-btn" @click="viewSiteListFn(record)">查看</a-button>
      </div>
    </template>
    <!-- OTA未匹配的车型数量 -->
    <template #channelModel="{ record }">
      <div class="channel-model-warpper" v-if="record.channelModel?.length > 0">
        <div class="channel-model-list">
          <div class="channel-model-item" v-for="(item, index) in record.channelModel" :key="index">
            {{ `${item.sourceIdName}: ${item.count}` }}
          </div>
        </div>
        <!-- 去匹配，按钮权限同 OTA渠道管理-编辑，当渠道未匹配数量有一个不为0时展示-->
        <div class="to-match" v-if="record.channelModel?.length > 0 && record.channelModel.some((item) => item.count)">
          <a-button v-permission="`svms:business:channel:ota.edit`" type="outline" size="mini" class="view-btn" @click="toMatchClick"
            >去匹配</a-button
          >
        </div>
      </div>
    </template>
    <!-- 更新信息 -->
    <template #updateInfo="{ record }">
      <template v-if="record.updateUserName || record.updateTime">
        <div>{{ record.updateUserName }}</div>
        <div>{{ record.updateTime }}</div>
      </template>
    </template>
    <!-- 模板状态 -->
    <template #model-status="{ record }">
      <status-tag :value="record.status" :label="record.statusStr" />
      <!-- <templateStatus :record="record" /> -->
    </template>
  </table-index>
  <!-- 反写价格弹窗 -->
  <write-price-modal ref="writePriceModalRef" />
  <!-- 反写价格介绍弹窗-无反写价格落地页权限时展示 -->
  <reversePriceModal ref="reversePriceModalRef" />
</template>

<script setup name="CarModelPriceListShortOrderConfig">
  import { ref, inject, onMounted, onBeforeUnmount } from 'vue'
  import { useTable, useFetchTableDataApi } from '@/hooks/table'
  import templateName from './template-name.vue'
  import templateStatus from './template-status.vue'
  import writePriceModal from './write-price-modal.vue'
  import guide from './guide.vue'
  import { getTemplateList } from '@/api/business/price.js'
  import useNavigate from '@/hooks/useNavigate'
  import useUserStore from '@/store/modules/user'
  import { usePermission } from '@/hooks/usePermission'
  import reversePriceModal from './reverse-price-modal.vue'
  const { redirectTo } = useNavigate()
  const emit = defineEmits(['viewSiteList', 'addTemplate', 'editTemplate', 'toggleStatus'])
  const queryParam = inject('queryParam')

  const userStore = useUserStore()

  // 查看门店
  const viewSiteListFn = (record) => emit('viewSiteList', record)
  // 模板启用停用
  const toggleStatusFn = (record, operateName) => emit('toggleStatus', record, operateName)

  // 一键反写价格弹窗
  const writePriceModalRef = ref(null)

  // 反写价格介绍弹窗
  const reversePriceModalRef = ref(null)

  // 去匹配
  const toMatchClick = () => {
    redirectTo(`/business/channel/ota`)
  }

  // table 配置
  const tableHeight = ref('600px')
  const calcTableHeightFn = () => {
    const clientHeight = document.querySelector('.main-body')?.getBoundingClientRect().height || 0
    const tableHeaderHeight = document.querySelector('.arco-table-header')?.getBoundingClientRect().height || 41
    const tableFooterHeight = document.querySelector('.table-footer-container')?.getBoundingClientRect().height || 52
    tableHeight.value = clientHeight - tableHeaderHeight - tableFooterHeight - 70
  }
  onMounted(() => {
    calcTableHeightFn()
    window.addEventListener('resize', calcTableHeightFn)
  })
  onBeforeUnmount(() => {
    window.removeEventListener('resize', calcTableHeightFn)
  })
  const table = useTable({
    tableHeight,
    columns: [
      { title: '模板名称', dataIndex: 'templateName', slotName: 'templateName' },
      { title: '车型数量', dataIndex: 'totalModelNum' },
      {
        title: '应用门店数',
        dataIndex: 'siteNum',
        slotName: 'siteNum',
        titleTooltipContent: '未匹配门店无法反写价格，请先配置所有门店保证反写顺利',
      },
      // { title: '未配置车型价格数量', width: 200, dataIndex: 'noModelNum' },
      {
        title: 'OTA未匹配的车型数量',
        dataIndex: 'channelModel',
        slotName: 'channelModel',
        width: 200,
        titleTooltipContent: '未匹配的车型无法反写价格，请先完成各渠道车型匹配在反写价格',
      },
      { title: '操作人及时间', dataIndex: 'updateInfo', slotName: 'updateInfo', width: 180 },
      { title: '模板状态', dataIndex: 'statusStr', width: 128, slotName: 'model-status' },
    ],
    operates: [
      {
        label: '编辑价格',
        permission: 'svms:business:price:car-model.edit',
        method: (record) => emit('editTemplate', record),
      },
      {
        label: '启用',
        permission: 'svms:business:price:car-model.enable',
        // 停用状态显示
        show: (record) => record.status == 0 && record.templateType != 1,
        method: (record) => toggleStatusFn(record, '启用'),
      },
      {
        label: '停用',
        permission: 'svms:business:price:car-model.disable',
        // 启用状态显示
        show: (record) => record.status == 1 && record.templateType != 1,
        method: (record) => toggleStatusFn(record, '停用'),
      },
      {
        label: '一键反写价格',
        permission: 'svms:business:price:car-model.writePrice',
        // 启用状态以及商户开通了反向写价格增值服务
        show: (record) => record.status == 1 && userStore.epChannelPriceSync,
        method: (record) => writePriceModalRef.value.open('single', record),
      },
    ],
    buttons: [
      {
        // 没有开通反向写价格时展示
        label: '批量反写价格',
        permission: userStore.epChannelPriceSync ? 'svms:business:price:car-model.batchWritePrice' : undefined,
        method: () => {
          // 未开通反向写价格增值服务
          if (!userStore.epChannelPriceSync) {
            // 有权限，跳转落地页
            if (usePermission('svms:value-added:reverse-price-writing')) {
              redirectTo(`/value-added/reverse-price-writing`)
            } else {
              // 无权限，打开落地页弹窗
              reversePriceModalRef.value.open()
            }
          } else {
            writePriceModalRef.value.open('batch')
          }
        },
      },
      {
        label: '反写结果查询',
        permission: 'svms:business:channel:sync-ota-price',
        show: () => userStore.epChannelPriceSync,
        method: () => {
          redirectTo(`/business/channel/sync-ota-price`)
        },
      },
      {
        type: 'primary',
        icon: 'plus',
        label: '新增',
        permission: 'svms:business:price:car-model.add',
        method: (record) => emit('addTemplate', record),
      },
    ],
  })

  // 列表接口调用
  const loadData = useFetchTableDataApi(table, queryParam, getTemplateList)

  defineExpose({
    loadData,
  })
</script>

<style lang="less" scoped>
  .site-num-wrapper {
    font-size: 14px;
    .site-num-val {
      vertical-align: middle;
      line-height: 20px;
    }
  }
  .view-btn {
    border-radius: 2px;
    opacity: 1;
    border: 1px solid #1890ff;
    color: #1890ff;
    margin-left: 6px;
    height: 18px;
    line-height: 18px;
    padding: 0 8px;
    font-size: 12px;
    vertical-align: middle;
  }
  .to-match {
    text-align: center;
    margin-top: 7px;
  }
  .channel-model-warpper {
    .channel-model-list {
      display: flex;
      flex-wrap: wrap;
      .channel-model-item {
        flex: 0 0 50%;
        margin-bottom: 4px;
      }
      .channel-model-item:nth-of-type(even) {
        text-align: right;
      }
    }
  }
</style>
